package servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 这是一个HttpSession接口的应用演示Servlet，直接访问本Servlet查看运行结果。
 * @author Steven Suo
 *
 */
@WebServlet("/session.view")
public class SessionServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SessionServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//使用request对象的getSession()获取session，如果session不存在则创建一个
		HttpSession session  = request.getSession();
		//向session中保存一个String对象，保存的对象命名为"userName"
		session.setAttribute("userName", "Tomcat");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.append("<html>");
		//判断是否为新创建的session对象
		if (session.isNew()) {
			out.append("这是一个新创建的session对象，session id是:"+session.getId());
		}else{
			out.append("这是一个旧的session对象，session id是:"+session.getId());
			out.append("<br>");
			//获取Cookie，并从中找一个命名为JSESSIONID的Cookie
			Cookie[] cookies = request.getCookies();
			for (Cookie cookie : cookies) {
				if (cookie.getName().equals("JSESSIONID")) {
					out.append("找到一个名为JSESSIONID的Cookie ，其值为："+cookie.getValue()+"，你看是否与session id相同？");
				}
			}
		}
		out.append("</html>");
		out.close();
	}

}
